package com.qd.flow.listener;

import com.cdqidi.util.LockTemplate;
import com.qd.common.flow.constant.FlowConstants;
import com.qd.common.flow.domain.event.FlowTaskStateDTO;
import com.qd.common.flow.enums.FlowEventType;
import com.qd.panda.model.UserWalletRefundApply;
import com.qd.panda.service.wallet.user.UserWalletRefundApplyService;
import com.qd.panda.service.wallet.user.WalletService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.function.Supplier;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjk
 * @create 2024-02-21 12:37
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FlowListenerImpl implements FlowListener {
    private final WalletService walletService;
    private final UserWalletRefundApplyService userWalletRefundApplyService;

    @Override
    public void notify(Supplier<FlowTaskStateDTO> supplier) {
        FlowTaskStateDTO flowTaskStateDTO = supplier.get();
        String name = flowTaskStateDTO.getFlowEventType().name();
        if (name.equals(FlowEventType.FINISH.name())) {
            //流程结束
            toDo(flowTaskStateDTO);
        } else if (name.equals(FlowEventType.STOP.name())) {
            //流程终止
            toDo(flowTaskStateDTO);
        } else {
            log.info("流程事件不处理：{}", name);
        }
    }

    public void toDo(FlowTaskStateDTO flowTaskStateDTO) {
        if (flowTaskStateDTO.getProcessCode().equals(FlowConstants.PROCESS_CODE_WALLET_REFUND)) {
            UserWalletRefundApply userWalletRefundApply = userWalletRefundApplyService.getById(flowTaskStateDTO.getBid());
            if (null == userWalletRefundApply) {
                return;
            }
            if (flowTaskStateDTO.getApprovalStatus() == FlowConstants.APPROVAL_STATUS_1) {
                LockTemplate.execute(userWalletRefundApply.getApplicant(), () -> {
                    walletService.updateApprovalStatus(flowTaskStateDTO);
                    return null;
                });
            } else {
                walletService.updateApprovalStatus(flowTaskStateDTO);
            }
        }
    }
}